package cn.wolfcode.producer.send;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
public class SendController {

    @Autowired
    private RocketMQTemplate template;

    @RequestMapping("send")
    public String send(String msg){
        //发送消息
        template.syncSend("hello",msg);
        return "ok (^_−)☆";
    }
    //同步消息发送
    @RequestMapping("syncSend")
    public String syncSend(String msg){
        //发送消息
        template.syncSend("method",msg);
        return "ok (^_−)☆";
    }
    //异步消息发送
    @RequestMapping("asyncSend")
    public String asyncSend(String msg){
        //创建消息对象 先获得消息构建对象,然后构建出来消息对象
        MessageBuilder<String> messageBuilder = MessageBuilder.withPayload(msg);
        Message<String> message = messageBuilder.build();
        //发送消息
        template.asyncSend("method", message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("发送失败");
            }
        });
        return "ok (^_−)☆";
    }
    //一次消息发送
    @RequestMapping("sendOneWay")
    public String sendOneWay(String msg){
        //发送消息
        template.sendOneWay("method",msg);
        return "ok (^_−)☆";
    }

    //消费模式
    @RequestMapping("sendModel")
    public String sendModel(String msg){
        //发送消息
        template.syncSend("model2",msg);
        return "ok (^_−)☆";
    }
    //延时发送
    @RequestMapping("sendDelay")
    public String sendDelay(String msg){
        MessageBuilder<String> messageBuilder = MessageBuilder.withPayload(msg);
        Message<String> message = messageBuilder.build();
        //延迟十秒发送发送消息
        template.syncSend("delay",message,3000,3);
        return "ok (^_−)☆";
    }
    //设置消息标签
    //在发送的消息Topic:Tag 中间使用冒号隔开
    @RequestMapping("sendWithTag")
    public String sendWithTag(String msg,String tag){
        template.convertAndSend("filter:" + tag,msg);
        return "ok (^_−)☆";
    }
    //设置sql92语句
    @RequestMapping("sendWithSql")
    public String sendWithSql(String msg,String tag,String age){
        HashMap<String, Object> map = new HashMap<>();
        map.put("age",age);
        //设置系统的key值
        map.put(MessageConst.PROPERTY_KEYS,age);
        template.convertAndSend("filter:" + tag,msg,map);
        return "ok (^_−)☆";
    }
}
